package cn.xinfei.xdecision.feign;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.IOException;

@Slf4j
public class OkHttpLogInterceptor implements Interceptor {
    private static String TAG = "LoggerInterceptor";
    public static volatile boolean isDebug = true;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long t1 = 0;
        if (isDebug) {
            //1.请求前--打印请求信息
            t1 = System.nanoTime();
            log.info(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
        }
        //2.网络请求
        Response response = chain.proceed(request);
        if (isDebug) {
            //3.网络响应后--打印响应信息
            long t2 = System.nanoTime();
//            ResponseBody responseBody = response.peekBody(1024 * 1024);
//            System.out.println("responseBody====:"+  responseBody.string());
            log.info(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        }

        return response;

    }
}
